﻿using System;
using System.Threading.Tasks;

#nullable disable
namespace BeetleX.XRPC.Clients
{
    internal class AnyCompletionSource<T> : TaskCompletionSource<T>, IAnyCompletionSource
    {
        public void Success(object data) => this.TrySetResult((T)data);

        public void Error(Exception error) => this.TrySetException(error);

        public ClientActionHandler ClientActionHandler { get; set; }

        public async void WaitResponse(System.Threading.Tasks.Task<RPCPacket> task)
        {
            try
            {
                RPCPacket rpcPacket = await task;
                if (rpcPacket.Status != (short)200)
                    this.Error(new XRPCException(rpcPacket.Data?.Length > 0 ? rpcPacket.Data[0].ToString() : null));
                else if (rpcPacket.Paramters > 0)
                    this.Success(rpcPacket.Data[0]);
                else
                    this.Success(new object());
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
        }

        public System.Threading.Tasks.Task GetTask() => (System.Threading.Tasks.Task)this.Task;
    }
}
